import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:tender_flutter/constant/app_constant.dart';
import 'package:tender_flutter/constant/resource_path.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/home/api/api_payorder.dart';
import 'package:tender_flutter/page/person/model/pay_order_entity.dart';
import 'package:tender_flutter/page/person/model/pay_params.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/style/font_style.dart';
import 'package:tender_flutter/utils/pay.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/utils/utils.dart';
import 'package:tender_flutter/widgets/base_appbar.dart';

class PaymentPage extends StatefulWidget {
  /// 商品下单参数
  final PayParams payParams;

  const PaymentPage({Key key, @required this.payParams}) : super(key: key);

  @override
  _PaymentPageState createState() => _PaymentPageState();
}

class _PaymentPageState extends State<PaymentPage> {
  String selImg = RPath.imgPath + "icon_box_sel.png";
  String norImg = RPath.imgPath + "icon_box_nor.png";

  /// 支付渠道
  int _payChannel = AppConstant.PAY_CHANNEL_WX;

  /// 开始支付
  Future _startPay() async {
    ToastUtils.showLoading("支付中");

    /// 第一步： 创建订单
    ApiResponse<PayOrderEntity> response = null;
    if (widget.payParams.orderType == AppConstant.PAY_ORDER_WAIT) {
      response = await ApiPayOrder.waitOrderPay<PayOrderEntity>(
          orderId: widget.payParams.goodsId, type: _payChannel);
    } else if (widget.payParams.orderType == AppConstant.PAY_ORDER_MEMBER) {
      response = await ApiPayOrder.getPayOrder<PayOrderEntity>(
          goodsId: widget.payParams.comboId, channelType: _payChannel);
    } else if (widget.payParams.orderType == AppConstant.PAY_ORDER_MARKET_TOP) {
      response = await ApiPayOrder.marketPlaceTop<PayOrderEntity>(
          id: widget.payParams.goodsId,
          pushTopId: widget.payParams.comboId,
          station: _payChannel);
    } else {
      ToastUtils.dismissLoading();
      ToastUtils.show("商品信息错误");
    }

    /// 第二部： 调起第三方开始支付
    if (response.status == Status.SUCCESS) {
      bool res = await PayUtils.startPay(
          _payChannel,
          response.result,
          (isSuccess, errCode, msg) => {
                ToastUtils.dismissLoading(),
                if (isEmpty(msg)) {ToastUtils.show(msg)},
                if (isSuccess)
                  {
                    if (widget.payParams.orderType ==
                            AppConstant.PAY_ORDER_WAIT ||
                        widget.payParams.orderType ==
                            AppConstant.PAY_ORDER_MEMBER)
                      {
                        LRouter.navigatorCtx(context).popUntilRoot(),
                      }
                    else
                      {
                        LRouter.navigatorCtx(context)
                            .popAndPush(Routes.publishSuccessPage)
                      }
                  }
              });
      ToastUtils.dismissLoading();
      if (!res) {
        ToastUtils.show("支付启用失败");
      }
    }
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeColors.colorWhite,
      appBar: _initAppBar(),
      body: _initBody(),
    );
  }

  /// 导航
  Widget _initAppBar() {
    return BaseAppBar(
      context,
      Text("支付详情", style: FonStyle.navTextStyle()),
      backgroundColor: ThemeColors.colorWhite,
    );
  }

  /// 内容体
  Widget _initBody() {
    return SingleChildScrollView(
        child: Column(children: [
      Container(
          padding: EdgeInsets.symmetric(vertical: ScreenAdapter.height(60)),
          child: Column(children: [
            Text("¥" + widget.payParams.goodsPrice.toString() ?? "0",
                style: TextStyle(
                    color: ThemeColors.colorType1,
                    fontSize: ScreenAdapter.sp(60),
                    fontWeight: FontWeight.bold)),
            Text(widget.payParams.goodsDes ?? "-",
                style: TextStyle(
                    color: ThemeColors.colorType1,
                    fontSize: ScreenAdapter.sp(24))),
          ])),
      Divider(height: ScreenAdapter.height(20), color: ThemeColors.colorType48),
      Padding(
        padding: EdgeInsets.symmetric(horizontal: ScreenAdapter.width(30)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisSize: MainAxisSize.min,
          children: [
            Padding(
                padding:
                    EdgeInsets.symmetric(vertical: ScreenAdapter.height(30)),
                child: Text("选择支付方式",
                    style: TextStyle(
                      color: ThemeColors.colorType1,
                      fontSize: ScreenAdapter.sp(32),
                    ))),
            Divider(height: 1, color: ThemeColors.colorType49),
            Padding(
                padding:
                    EdgeInsets.symmetric(vertical: ScreenAdapter.height(30)),
                child: InkWell(
                    onTap: () {
                      setState(() {
                        _payChannel = AppConstant.PAY_CHANNEL_WX;
                      });
                    },
                    child: Row(children: [
                      Image.asset(RPath.imgPath + "icon_pay_wx.png",
                          width: ScreenAdapter.width(40),
                          height: ScreenAdapter.width(40)),
                      SizedBox(width: ScreenAdapter.width(20)),
                      Text("微信",
                          style: TextStyle(
                            color: ThemeColors.colorType1,
                            fontSize: ScreenAdapter.sp(32),
                          )),
                      Expanded(child: SizedBox()),
                      Image.asset(
                          _payChannel == AppConstant.PAY_CHANNEL_WX
                              ? selImg
                              : norImg,
                          width: ScreenAdapter.width(40),
                          height: ScreenAdapter.width(40)),
                    ]))),
            Divider(height: 1, color: ThemeColors.colorType49),
            Padding(
                padding:
                    EdgeInsets.symmetric(vertical: ScreenAdapter.height(30)),
                child: InkWell(
                    onTap: () {
                      setState(() {
                        _payChannel = AppConstant.PAY_CHANNEL_ALi;
                      });
                    },
                    child: Row(children: [
                      Image.asset(RPath.imgPath + "icon_pay_ali.png",
                          width: ScreenAdapter.width(40),
                          height: ScreenAdapter.width(40)),
                      SizedBox(width: ScreenAdapter.width(20)),
                      Text("支付宝支付",
                          style: TextStyle(
                            color: ThemeColors.colorType1,
                            fontSize: ScreenAdapter.sp(32),
                          )),
                      Expanded(child: SizedBox()),
                      Image.asset(
                          _payChannel == AppConstant.PAY_CHANNEL_ALi
                              ? selImg
                              : norImg,
                          width: ScreenAdapter.width(40),
                          height: ScreenAdapter.width(40)),
                    ]))),
            Divider(height: 1, color: ThemeColors.colorType49),
          ],
        ),
      ),
      _initSubmitBtn()
    ]));
  }

  /// 提交按钮
  Widget _initSubmitBtn() {
    return Container(
        height: ScreenAdapter.height(90),
        width: double.infinity,
        margin: EdgeInsets.symmetric(
            vertical: ScreenAdapter.height(100),
            horizontal: ScreenAdapter.width(30)),
        decoration: BoxDecoration(
            color: ThemeColors.colorType6,
            borderRadius: BorderRadius.circular(ScreenAdapter.width(14))),
        child: FlatButton(
            onPressed: () {
              _startPay();
            },
            child: Text("立即支付",
                style: TextStyle(
                    color: ThemeColors.colorWhite,
                    fontSize: ScreenAdapter.sp(32)))));
  }
}
